<?php
namespace catchAdmin\archives\service;

use catcher\exceptions\FailedException;
use app\common\model\PatientInfo as PatientInfoModel;
use app\common\model\Follow as FollowModel;
use app\common\model\Followtask as FollowtaskModel;
use app\common\model\PatientRecord as PatientRecordModel;

class InformationService
{
    /**
     * 随访电话-手机号获取患者信息
     * @param string $mobile
     * @return array
     */
    public function getFoTelPatientInfo(string $mobile): array
    {
        $field = "id,patientId,name,sex,contactAddress,presentAddress,timeLine.diagnosis";
        $info = (new PatientInfoModel())->getOneData(['presentTelphone' => $mobile], $field);

        if (empty($patientInfo))
        {
            throw new FailedException("无此患者信息");
        }

        $patientInfo = $info->toArray();
        
        //获取最新一次就诊信息
        $patientInfo['timeLine']  = array_shift($patientInfo['timeLine']);
        $patientInfo['diagnosis'] = $patientInfo['timeLine']['diagnosis'];
        unset($patientInfo['timeLine']);

        //获取最新一次随访记录
        $followInfo = (new FollowModel())->getOneData(['patientId' => $patientInfo['patientId']], 'task_id');     
        $taskInfo = (new FollowtaskModel())->getOneData(['id' => $followInfo['task_id']], 'taskname');
        $patientInfo['taskname'] = $taskInfo['taskname'];
        
        return  $patientInfo;
    }

    /**
     * 新增患者信息
     * @param array $data
     * @return bool
     */
    public function addPatientInfo(array $data=[]): bool
    {
        try {
            $param = [
                'name' => (string)$data['name'],
                'sex' => (string)$data['sex'],
                'idType' => 1,
                'idno' => (string)$data['idno'],
                'birthdate' => isset($data['birthdate'])?(string)$data['birthdate']:'',
                'inage' => isset($data['inage'])?(int)$data['inage']:'',
                'patientId' => (string)$data['idno'],
                'medicalRecordsNo' => isset($data['medicalRecordsNo'])?(string)$data['medicalRecordsNo']:'',
                'presentTelphone' => (string)$data['mobile'],
                'liveStatus' => '1',
                'deleted_at' => 0,
                'created_time' => date('Y-m-d H:i:s'),
                'created_ymd' => date('Y-m-d'),
            ];

            $record = [];
            $where = [];
            switch ($data['type']) {
                case 1:
                    $field = 'outList';
                    $record['type'] = $param['outList']['type'] = 1;
                    $record['clinicNo'] = $param['outList']['clinicNo'] = isset($data['clinicNo'])?(string)$data['clinicNo']:'';
                    $record['patientId'] = $param['outList']['patientId'] = (string)$data['idno'];
                    $record['visitTime'] = $param['outList']['visitTime'] = date("Y-m-d", strtotime($data['visit_time']));
                    $record['attendingDoctorId'] = $param['outList']['attendingDoctorId'] = $data['doctorList']['doctor_code'];
                    $record['attendingDoctorName'] = $param['outList']['attendingDoctorName'] = $data['doctorList']['doctor_name'];
                    $record['deptName'] = $param['outList']['deptName'] = $data['deptList']['deptName']??'';
                    $record['deptId'] = $param['outList']['deptId'] = $data['deptList']['deptId']??'';
                    $record['diseaseList']['disease'] = $param['outList']['diseaseList']['disease'] = $data['disease']??[];
                    break;
                case 2:
                    $field = 'inList';
                    $record['type'] = $param['inList']['type'] = 2;
                    $record['inhospitalNo'] = $param['inList']['inhospitalNo'] = isset($data['inhospitalNo'])?(int)$data['inhospitalNo']:'';
                    $record['patientId'] = $param['inList']['patientId'] = (string)$data['idno'];
                    $record['inhospitalDate'] = $param['inList']['inhospitalDate'] = (string)$data['visit_time'];
                    $record['inchargeDoctorNo'] = $param['inList']['inchargeDoctorNo'] = $data['doctorList']['doctor_code'];
                    $record['inchargeDoctorName'] = $param['inList']['inchargeDoctorName'] = $data['doctorList']['doctor_name'];
                    $record['diseaseNo'] = $param['inList']['diseaseNo'] = $data['disease']['diseaseCode']??'';
                    $record['diagnose'] = $param['inList']['diagnose'] = $data['disease']['diseaseName']??'';
                    $record['inhospitalDeptCode'] = $param['inList']['inhospitalDeptCode'] = $data['deptList']['deptName']??'';
                    break;
                case 3:
                    $field = 'hoList';
                    $record['type'] = $param['hoList']['type'] = 3;
                    $record['inhospitalNo'] = $param['hoList']['inhospitalNo'] = isset($data['inhospitalNo'])?(int)$data['inhospitalNo']:'';
                    $record['patientId'] = $param['hoList']['patientId'] = (string)$data['idno'];
                    $record['outhospitalDate'] = $param['hoList']['outhospitalDate'] = (string)$data['visit_time'];
                    $record['inchargeDoctorNo'] = $param['hoList']['inchargeDoctorNo'] = $data['doctorList']['doctor_code'];
                    $record['inchargeDoctorName'] = $param['hoList']['inchargeDoctorName'] = $data['doctorList']['doctor_name'];
                    $record['diseaseNo'] = $param['hoList']['diseaseNo'] = $data['disease']['diseaseCode']??'';
                    $record['diagnose'] = $param['hoList']['diagnose'] = $data['disease']['diseaseName']??'';
                    $record['outhospitalDeptCode'] = $param['outList']['outhospitalDeptCode'] = $data['deptList']['deptName']??'';
                    break;
                default:
                    throw new FailedException("type类型错误");
            }

            $where[] = ['patientId', '=', (string)$data['idno']];
            $is_exist = (new PatientInfoModel())->where($where)->field($field)->find();
            if (!empty($is_exist[$field])) {
                throw new FailedException("患者信息已存在");
            }

            $record['deleted_at'] = 0;
            $record['created_time'] = date('Y-m-d H:i:s');
            $record['created_ymd'] = date('Y-m-d');

            (new PatientInfoModel())->addData($param);
            (new PatientRecordModel())->addData($record);
            return true;
        } catch (\Exception $exception) {
            throw new FailedException($exception->getMessage());
        }
    }

    /**
     * 更新失访后的患者，联系方式更新状态
     * @param $id
     * @param string $mobile
     * @param int $type 1 患者列表更新，2 号码维护更新
     * @return bool
     */
    public function upLostPhoneStatus($id, string $mobile, int $type = 1): bool
    {
        $info = (new PatientInfoModel())->where([
            ['id', '=', $id],
            ['lost_access', '=', 1]
        ])->findOrEmpty()->toArray();

        if ($info) {
            $where[] = ['id', '=', $id];

            if ($type == 1) {
                $where[] = ['presentTelphone', '=', $mobile];
            }else{
                $where[] = ['relationInfo.mobile', '=', $mobile];
            }

            $isExist = (new PatientInfoModel())->where($where)->findOrEmpty()->toArray();

            if (!$isExist) {
                $data['lost_access_phone_status'] = 1;
                (new PatientInfoModel())->saveData($id, $data);
            }
        }
        return true;
    }
}
